package com.tcs.test.http.proxy;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class HttpProxyVPN {
	
	private final Logger logger = LoggerFactory.getLogger(HttpProxyVPN.class);
	
	private String url = "http://www.xicidaili.com/nn/";
	
	public  Document getDoc(String url) throws IOException {
		Document doc = Jsoup.connect(url + "/")
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
	            .header("Accept-Encoding", "gzip, deflate, sdch")
	            .header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6")
	            .header("Cache-Control", "max-age=0")
	            .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
	            .header("Cookie", "Hm_lvt_7ed65b1cc4b810e9fd37959c9bb51b31=1462812244; _gat=1; _ga=GA1.2.1061361785.1462812244")
	            .header("Host", "www.kuaidaili.com")
	            .header("Referer", "http://www.kuaidaili.com/free/outha/")
	            .timeout(30 * 1000)
	            .get();
		return doc;
	}
            
	public String[] getVPNIp(String content) {
		String ipReg = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3} \\d{1,6}";
		 Pattern ipPtn = Pattern.compile(ipReg);
		 Matcher m = ipPtn.matcher(content);
		 
         while (m.find()) {
        	 String[] strs = m.group().split(" ");
             if (checkProxy(strs[0], Integer.parseInt(strs[1]))) {
            	 logger.info( " 获取到可用代理IP : {} " , Arrays.toString(strs));
                 return strs;
             }
         }
		return null;
	}
	
	 /**
     * 判断ip和端口是否有效
     * @param ip
     * @param port
     * @return
     */
    private static boolean checkProxy(String ip, Integer port) {
        try {
            //http://1212.ip138.com/ic.asp 可以换成任何比较快的网页
            Jsoup.connect("http://1212.ip138.com/ic.asp")
                    .timeout(2 * 1000)
                    .proxy(ip, port)
                    .get();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Test
    public void queryIp() {
    	try {
    		String url = "http://piping.mogumiao.com/proxy/api/get_ip_al?appKey=996ec873f55e45cf902af4f056fd9669&count=3&expiryDate=0&format=1&newLine=2";
    		
    		Map<String,String> ConfigMap = Maps.newHashMap();
    		ConfigMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    		ConfigMap.put("Accept-Encoding", "gzip, deflate, sdch");
    		ConfigMap.put("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4");
    		
    		String proxyGo = Jsoup.connect(url).get().text();
    		JSONObject jsonOBject = JSONObject.fromObject(proxyGo);
    		JSONArray jsonArray = JSONArray.fromObject(jsonOBject.get("msg"));
//    		String tempUrl = "http://service.tf099.com/sisuers_web/a/content/detail?id=4986";
    		String tempUrl = "http://wb-sys.tpddns.cn:1001/caiChang-system-web/index.html";
//    		String tempUrl = "https://www.yiibai.com/jackson/jackson_first_application.html";
//    		String [] vpn = this.getVPNIp(this.getDoc(url).text());
    		logger.info(" data : {}" , jsonOBject.toString());
    		for (int i = 0; i < jsonArray.size(); i++) {
    			JSONObject jsonOBject1 = JSONObject.fromObject(jsonArray.get(i));
    			Document doc;
				try {
					doc = Jsoup.connect(tempUrl)
							.proxy(jsonOBject1.getString("ip"),jsonOBject1.getInt("port"))
							.timeout(5 * 1000)
							.get();
					logger.info(" ip : {} , port : {} , : {} , \n doc : {} " , jsonOBject1.getString("ip"), jsonOBject1.getInt("port") , doc.html());
				} catch (Exception e) {
					logger.error(" ip : " + jsonOBject1.getString("ip") + "prot : " + jsonOBject1.getInt("port") , e);
				}
    		}
		} catch (IOException e) {
			logger.error( "" , e);
		}
    }
}
